import { Init, Provide, Inject } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { MemberUserInfoEntity } from '../entity/info';
import { DemoUserInfoEntity } from '../../demo/entity/info';

import { UserFeedbackInfoEntity } from "../../userfeedback/entity/info"

import { AnchorDynamicEntity } from "../../anchorDynamic/entity/dynamic"

/**
 * member模块-用户信息
 */
@Provide()
export class MemberUserInfoService extends BaseService {
  @InjectEntityModel(MemberUserInfoEntity)
  memberUserInfoEntity: Repository<MemberUserInfoEntity>;

  @InjectEntityModel(DemoUserInfoEntity)
  demoUserInfoEntity: Repository<DemoUserInfoEntity>;

  @InjectEntityModel(UserFeedbackInfoEntity)
  userFeedbackInfoEntity: Repository<UserFeedbackInfoEntity>;

  @InjectEntityModel(AnchorDynamicEntity)
  anchorDynamicEntity: Repository<AnchorDynamicEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.memberUserInfoEntity);
  }

  @Inject()
  ctx;

  async createMember(BodyData: any) {
    console.log(BodyData, 'BodyData')
    let { username, password, passwordSecond, avatar } = BodyData
    let param = {
      username,
      password,
      nickname: "普通用户",
      age: 18,
      level: 0,
      points: 0,
      balance: 0,
      status: 1,
      avatar,
      registerTime: new Date(),
      lastLogin: new Date(),
      openTime: new Date(),
    }
    if (!password || !passwordSecond) {
      throw new Error('请输入密码');
    }
    if (passwordSecond != password) {
      throw new Error('两次密码输入不一样');
    }
    // 查找重名
    let memberItem: any = await this.memberUserInfoEntity.findOneBy({ username })
    if (memberItem) {
      throw new Error('用户名已存在');
    }
    let res = await super.add(param);
    return res
  }

  async updateMember(BodyData: any) {
    console.log(BodyData, 'BodyData')
    let id = this.ctx.header.token
    let { age, nickname } = BodyData
    let memberItem: any = await this.memberUserInfoEntity.findOneBy({ id })
    let param: any = memberItem
    if (nickname) {
      param.nickname = nickname
    } else {
      param.nickname = memberItem.nickname
    }
    if (age) {
      param.age = age
    }
    // let memberRepeat: any = await this.memberUserInfoEntity.findOneBy({ nickname })
    let sql = "select * from demo_user_info where nickname = '" + param.nickname + "' and id != " + Number(id)
    console.log(sql, 'sql')
    let memberRepeat: any = await this.nativeQuery(sql);
    // 查找重名
    console.log(memberRepeat, 'memberRepeat')
    if (memberRepeat.length) {
      throw new Error('昵称已存在');
    }
    let res = await super.update(param);
    return res
  }

  async updatePassword(BodyData: any) {
    console.log(BodyData, 'BodyData')
    let { id, oldPassword, newPassword } = BodyData
    let memberItem: any = await this.memberUserInfoEntity.findOneBy({ id })
    let param: any = memberItem
    if (param.password != oldPassword) {
      throw new Error('原密码不正确');
    }
    param.password = newPassword
    let res = await super.update(param);
    return res
  }

  async login(BodyData: any) {
    let { username, password } = BodyData
    let memberItem: any = await this.memberUserInfoEntity.findOneBy({ username })
    if (!memberItem) {
      throw new Error('用户不存在');
    } else {
      if (password == memberItem.password) {
        let item = JSON.parse(JSON.stringify(memberItem))
        let sql = "select * from dict_info where typeId = 23"
        let res = await this.nativeQuery(sql);
        let itemLevel = res.find(o => o.value == item.level)
        item.password = null
        item.levelName = itemLevel.name
        return item
      } else {
        throw new Error('密码不正确');
      }
    }
  }

  async getUserInfo() {
    let userId = this.ctx.header.token
    let memberItem: any = await this.memberUserInfoEntity.findOneBy({ id: userId })
    let sql = "select * from dict_info where typeId = 23"
    let res = await this.nativeQuery(sql);
    let itemLevel = res.find(o => o.value == memberItem.level)
    memberItem.password = null
    memberItem.levelName = itemLevel.name
    return memberItem
  }

  // 获取banner
  async baner(BodyData: any) {
    let sql = "select * from bannersetting_banner"
    let res = await this.nativeQuery(sql);
    return res
  }

  // 获取主播
  async anchorList(BodyData: any) {
    let { types } = BodyData
    let sql = "select * from demo_user_info where source =" + types + " ORDER BY createTime DESC"
    let res = await this.nativeQuery(sql);
    return res
  }

  // 获取照片分类
  async dictList(keyId: any = 21) {
    let sql = "select * from dict_info where typeId = " + keyId
    let res = await this.nativeQuery(sql);
    return res
  }

  // 获取照片列表
  async photoList(queryData: any) {
    let userId = this.ctx.header.token

    let category = queryData.category ? (` and category = '${queryData.category}'`) : ''
    let sql = "select * from anchor_info where status = 1 " + category + " ORDER BY createTime DESC"
    let res = await this.sqlRenderPage(sql, queryData, false);
    let list = res.list.map(o => o.id).join(',')
    let anchor = res.list.map(o => Number(o.anchor)).join(',')
    let anchorList = []
    let anchorSql = "select * from demo_user_info where id IN ( " + anchor + " )"
    anchorList = await this.nativeQuery(anchorSql);
    if (userId) {
      let photoSql = "select * from collection_info where collectionId IN ( " + list + " ) and status = 1 and userId = " + Number(userId)
      let data: any = await this.nativeQuery(photoSql);


      let memberItem: any = await this.memberUserInfoEntity.findOneBy({ id: userId })
      let resList = []
      if (data) {
        resList = data.map(o => Number(o.collectionId)).join(',')
      }
      let isVip = memberItem.level > 0 && memberItem.expireTime > new Date()
      res.list.forEach(o => {
        let item = anchorList.find(o1 => o1.id == o.anchor)
        o.anchor = item
        o.isVipCurrentUser = o.permission == 0 && !isVip
        o.isVip = o.permission == 0 || (o.permission == 1 && isVip) // 不是vip
        o.isVipExpire = memberItem.expireTime < new Date()
        o.isCollect = resList.includes(o.id)
        o.imageNum = JSON.parse(JSON.stringify(o.image)).length
        o.image = o.isVip ? o.image : o.image.splice(0, 3)
        o.isLogin = true
      })
    } else {
      res.list.forEach(o => {
        let item = anchorList.find(o1 => o1.id == o.anchor)
        o.anchor = item
        o.imageNum = JSON.parse(JSON.stringify(o.image)).length
        o.image = o.isVip ? o.image : o.image.splice(0, 3)
        o.isLogin = false
      })
    }

    return res
  }

  // 获取主播动态
  async dynamicList(queryData: any) {
    let anchorId = queryData.anchorId ? (`where anchorId = '${queryData.anchorId}'`) : (`where anchorId = '${queryData.anchorId}'`)
    let sql = "select * from anchor_dynamic " + anchorId + " ORDER BY createTime DESC"
    console.log(sql, 'sql', queryData)
    let res = await this.sqlRenderPage(sql, queryData, false);
    if (queryData.anchorId && res.list.length) {
      let sqlIsBy = "select * from anchor_dynamic_type where userId = " + this.ctx.header.token + " and dynamicId in (" + res.list.map(o => o.id).join(',') + ") ORDER BY createTime DESC"
      let byRes = await this.nativeQuery(sqlIsBy)
      let byList = byRes.map(o => Number(o.dynamicId))
      res.list.forEach(o => {
        o.isBy = byList.includes(o.id)
        if (o.dynamicImages) {
          o.dynamicImgNum = JSON.parse(JSON.stringify(o.dynamicImages)).length - 1
          o.dynamicImages = o.isBy ? o.dynamicImages : o.dynamicImages.splice(0, 1)
        } else {
          o.dynamicImgNum = 0
          o.dynamicImages = []
        }
      })
    }
    console.log(res, 'resres')
    return res
  }

  // 查询主播动态
  async anchorDynamicList(queryData: any) {
    let anchorList: any = await this.demoUserInfoEntity.findBy({ source: queryData.source })
    let arr = anchorList.map(o => o.id).join(',')
    let sql = "select * from anchor_dynamic where anchorId in (" + arr + ") ORDER BY createTime DESC"
    let res = await this.sqlRenderPage(sql, queryData, false);
    if (queryData.source == 0) {
      let sqlIsBy = "select * from anchor_dynamic_type where userId = " + this.ctx.header.token + " and dynamicId in (" + res.list.map(o => o.id).join(',') + ") ORDER BY createTime DESC"
      let byRes = await this.nativeQuery(sqlIsBy)
      let byList = byRes.map(o => Number(o.dynamicId))
      res.list.forEach(o => {
        o.isBy = byList.includes(o.id)
        if (o.dynamicImages) {
          o.dynamicImgNum = JSON.parse(JSON.stringify(o.dynamicImages)).length - 1
          o.dynamicImages = o.isBy ? o.dynamicImages : o.dynamicImages.splice(0, 1)
        } else {
          o.dynamicImgNum = 0
          o.dynamicImages = []
        }
      })
    }
    return res
  }

  // 获取主播i详情
  async anchorInfo(queryData: any) {
    let id = this.ctx.header.token
    let anchorInfoData = `where id = '${Number(queryData.anchorId)}'`
    let sql = "select * from demo_user_info " + anchorInfoData
    let res = await this.nativeQuery(sql);
    let followSql = "select * from follow_user_info where followStatus = 1 and followId = " + Number(queryData.anchorId) + " and userId = " + id + " ORDER BY createTime DESC"
    let followRes = await this.nativeQuery(followSql);
    if (followRes.length) {
      res[0].isFollow = true
    } else {
      res[0].isFollow = false
    }
    return res[0]
  }

  // 获取通知 
  async inform(queryData: any) {
    let userId = this.ctx.header.token
    let anchorId = userId ? (`where status = 0 or (status = 1 and receiver = ${Number(userId)})`) : ''
    let sql = "select * from tasksystem_task_info " + anchorId + " ORDER BY createTime DESC"
    console.log(anchorId, sql, 'anchorId')
    let res = await this.sqlRenderPage(sql, queryData, false);
    return res
  }

  // 会员反馈  
  async userfeedback(BodyData: any) {
    let userId = this.ctx.header.token
    let { feedbackContent } = BodyData
    let psrams: any = {
      feedbackContent,
      feedbackType: 0,
      feedbackTime: new Date(),
      processStatus: 0,
      processor: "",
      processTime: new Date(),
      contactInfo: "",
      userId,
      remark: "",
      feedbackId: ""
    }
    let res = await this.userFeedbackInfoEntity.save(psrams)
    return res
  }

  // // 升级会员支付
  // async upgradeMemberPay(BodyData: any){
  //   let userId = this.ctx.header.token
  //   // let sql = "select * from dict_info where id = " + BodyData.id
  //   // let res = await this.nativeQuery(sql);
  //   // let goodsId,orderType,orderPayType
  //   // let res = await this.orderPayService.aliApp(goodsId=userId, orderType,orderPayType)
  //   // let monery = Number(res[0].remark)
  //   console.log(this,'this.orderPayService')
  //   return 'res'
  // }

  // 获取订单列表
  async orderList(queryData: any) {
    let userId = this.ctx.header.token
    let category = queryData.page ? (`where (anchorId = ${userId} and orderType = 2 ) or (memberId = ${userId} and orderType = 4)`) : ''
    let sql = "select * from order_info " + category + " ORDER BY createTime DESC"
    console.log(sql, 'sql')
    let res = await this.sqlRenderPage(sql, queryData, false);
    return res
  }

}
